package com.bbx.demo.protobuf;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;

public class ProtobufServer {

    private int port = 8094;

    public ProtobufServer() {
    }


    public static void main (String [] args) throws InterruptedException {
        ProtobufServerHandler protobufServerHandler = new ProtobufServerHandler();
        new ProtobufServer().start(protobufServerHandler);

    }

    public void start (ChannelHandler channelHandler) throws InterruptedException {
        NioEventLoopGroup bossEventExecutors = new NioEventLoopGroup();
        NioEventLoopGroup workerEventExecutors = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossEventExecutors, workerEventExecutors)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch)  {
                            ch.pipeline()
                                    //handler顺序与服务端 handler add 顺序保持一致，否则会报错
                                    .addLast(new ProtobufDecoder(DataInfoTest.DataInfo.getDefaultInstance()))
                                    .addLast(new ProtobufEncoder())
                                    .addLast(new ProtobufVarint32FrameDecoder())
                                    .addLast(new ProtobufVarint32LengthFieldPrepender())

                                    .addLast(channelHandler);
                        }
                    });
            ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
            channelFuture.channel().closeFuture().sync();
        } finally {
            bossEventExecutors.shutdownGracefully();
            workerEventExecutors.shutdownGracefully();
        }
    }
}
